<template>
  <div class="login">
    <div class="login_body">
      <h1>用户登录/注册</h1>
      <el-form label-width="70px" :model="ruleform" :rules="rules">
        <el-form-item label="用户名" prop="username">
          <el-input class="input_el" v-model="ruleform.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" class="input_el" v-model="ruleform.password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="toLogin">登录</el-button>
          <el-button>重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { login } from "@/http/api";
export default {
  data() {
    return {
      ruleform: {
        username: "",
        password: "",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 5,
            max: 20,
            message: "长度在 5 到 20 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 20, message: "长度在 6 到  个字符", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    //触发登录事件
    async toLogin() {
      // 将输入值传给接口
      const res = await login(this.ruleform);
      //   console.log(res);
      const { token } = res.result;
      //保存token
      localStorage.setItem("token", token);

      //如果第一次登录，没有redirect，成功之后直接跳转到Home
      const { redirect } = this.$route.query;
      if (!redirect) {
        this.$router.push({ name: "Home" });
      } else {
        this.$router.push({ path: redirect });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.login {
  width: 100%;
  height: 100%;
  position: relative;
  background-color: #324057;
  .login_body {
    width: 40%;
    height: 350px;
    border-radius: 10px;
    background-color: #fff;
    overflow: hidden;
    position: absolute;
    top: 25%;
    left: 30%;
    h1 {
      text-align: center;
      width: 100%;
      height: 40px;
      line-height: 40px;
    }
  }
}
.input_el {
  width: 95%;
}
</style>